/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2024-01-04 10:01:28
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-05-07 17:24:41
 * @FilePath: /yt-devops/lib/components/device/device_model_picker.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:yt_devops/model/device_obj/prompt_rule_model.dart';
import 'package:yt_devops/model/device_obj/properties_model.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/brn_row1_delegate.dart';

enum PickTypeEnum {
  enumType,
  minute,
}

class PickModel {
  String name;
  dynamic value;
  PickModel({required this.name, required this.value});
}

class DevicePicker extends StatefulWidget {
  final PropertiesModel model;

  final PromptRuleModel? ruleModel;

  final List<PickModel> list;

  /// 值
  final dynamic value;

  /// 是否可编辑
  final bool disable;

  /// 提示语
  final String? tip;

  final PickTypeEnum pickType;

  ///
  final bool required;

  /// 切换回调
  final void Function(PickModel)? onChanged;

  final void Function(DateTime, List<int>)? onTimeChanged;

  const DevicePicker(
      {super.key,
      required this.model,
      this.list = const [],
      this.ruleModel,
      this.value = '',
      this.disable = false,
      this.tip,
      this.required = false,
      this.pickType = PickTypeEnum.enumType,
      this.onTimeChanged,
      this.onChanged});

  @override
  State<DevicePicker> createState() => _DevicePickerState();
}

class _DevicePickerState extends State<DevicePicker> {
  PickModel? selectedModel;

  @override
  void initState() {
    getSelectedModel();
    super.initState();
  }

  @override
  void didUpdateWidget(covariant DevicePicker oldWidget) {
    getSelectedModel();
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: BrnTextSelectFormItem(
        title: widget.model.name!,
        value: widget.value,
        isEdit: !widget.disable,
        error: widget.tip ?? '',
        isRequire: widget.required,
        themeData: BrnFormItemConfig(
            errorPadding: EdgeInsets.zero,
            titleTextStyle: BrnTextStyle(
              fontSize: 14.sp,
              color: Colour.mainTextColor,
            ),
            hintTextStyle: BrnTextStyle(
              color: Colour.hintTextColor,
              fontSize: 14.sp,
            ),
            contentTextStyle: BrnTextStyle.withStyle(TextStyles.f14),
            disableTextStyle: BrnTextStyle.withStyle(TextStyles.lf14)),
        onTap: () {
          if (widget.pickType == PickTypeEnum.enumType) {
            showBottomPop(widget.model, widget.ruleModel);
          } else {
            showTimePicker(widget.model, widget.ruleModel);
          }
        },
      ),
    );
  }

  getSelectedModel() {
    selectedModel = widget.list
        .firstWhereOrNull((element) => element.value == widget.value);
    if (mounted) {
      setState(() {});
    }
  }

  /// 弹出底部弹窗
  void showBottomPop(PropertiesModel model, PromptRuleModel? ruleModel) {
    int selectedIndex = -1;

    List<String> bottomPopList = [];

    for (var i = 0; i < widget.list.length; i++) {
      var element = widget.list[i];
      bottomPopList.add(element.name);
      // 获取第一个相等值的索引
      if (widget.value == element.value && selectedIndex == -1) {
        selectedIndex = i;
      }
    }

    BrnMultiDataPicker(
      context: context,
      title: ruleModel?.title?.replaceAll('\${name}', model.name!) ??
          ResKey.pleSelect.tr,
      confirmClick: (indexList) {
        if (indexList.isNotEmpty) {
          widget.onChanged?.call(widget.list[indexList[0]]);
        }
      },
      delegate: Brn1RowDelegate(
        bottomPopList,
        firstSelectedIndex: selectedIndex,
      ),
    ).show();
  }

  showTimePicker(PropertiesModel model, PromptRuleModel? ruleModel) {
    String format;

    switch (widget.pickType) {
      case PickTypeEnum.minute:
        format = 'yyyy年,MM月,dd日,HH时:mm分';
        break;

      default:
        format = 'yyyy-MMMM-dd';
        break;
    }

    BrnDatePicker.showDatePicker(context,
        rootNavigator: true,
        pickerMode: BrnDateTimePickerMode.datetime,
        pickerTitleConfig: BrnPickerTitleConfig(
          titleContent: ruleModel?.title?.replaceAll('\${name}', model.name!) ??
              ResKey.pleSelect.tr,
        ),
        dateFormat: format, onConfirm: (dateTime, list) {
      widget.onTimeChanged?.call(dateTime, list);
    });
  }
}
